import { createSlice, PayloadAction } from '@reduxjs/toolkit';

interface Message {
  _id: string;
  senderId: string;
  recipientId: string;
  content: string;
  timestamp: number;
  isRead: boolean;
}

interface Friend {
  _id: string;
  username: string;
  avatar: string;
  uid: string;
  lastMessage?: Message;
  unreadCount: number;
}

interface FriendRequest {
  _id: string;
  senderId: string;
  recipientId: string;
  status: 'pending' | 'accepted' | 'rejected';
  timestamp: number;
}

interface MessageState {
  friends: Friend[];
  messages: { [key: string]: Message[] }; // 按好友ID分组的消息列表
  friendRequests: FriendRequest[];
  activeChat: string | null; // 当前聊天的好友ID
}

const initialState: MessageState = {
  friends: [],
  messages: {},
  friendRequests: [],
  activeChat: null,
};

const messageSlice = createSlice({
  name: 'message',
  initialState,
  reducers: {
    setFriends: (state, action: PayloadAction<Friend[]>) => {
      state.friends = action.payload;
    },
    addMessage: (state, action: PayloadAction<Message>) => {
      const { senderId, recipientId } = action.payload;
      const chatId = [senderId, recipientId].sort().join('-');
      if (!state.messages[chatId]) {
        state.messages[chatId] = [];
      }
      state.messages[chatId].push(action.payload);

      // 更新好友列表中的最后一条消息和未读数
      const friendId = senderId === state.activeChat ? recipientId : senderId;
      const friendIndex = state.friends.findIndex(f => f._id === friendId);
      if (friendIndex !== -1) {
        state.friends[friendIndex].lastMessage = action.payload;
        if (state.activeChat !== friendId) {
          state.friends[friendIndex].unreadCount++;
        }
      }
    },
    setActiveChat: (state, action: PayloadAction<string>) => {
      state.activeChat = action.payload;
      // 重置未读消息计数
      const friendIndex = state.friends.findIndex(f => f._id === action.payload);
      if (friendIndex !== -1) {
        state.friends[friendIndex].unreadCount = 0;
      }
    },
    addFriendRequest: (state, action: PayloadAction<FriendRequest>) => {
      state.friendRequests.push(action.payload);
    },
    updateFriendRequest: (state, action: PayloadAction<FriendRequest>) => {
      const index = state.friendRequests.findIndex(r => r._id === action.payload._id);
      if (index !== -1) {
        state.friendRequests[index] = action.payload;
      }
    },
    markMessagesAsRead: (state, action: PayloadAction<{ friendId: string }>) => {
      const { friendId } = action.payload;
      const chatId = [friendId, state.activeChat].sort().join('-');
      if (state.messages[chatId]) {
        state.messages[chatId] = state.messages[chatId].map(msg => ({
          ...msg,
          isRead: true,
        }));
      }
    },
  },
});

export const {
  setFriends,
  addMessage,
  setActiveChat,
  addFriendRequest,
  updateFriendRequest,
  markMessagesAsRead,
} = messageSlice.actions;

export default messageSlice.reducer;